# -*- coding: utf-8 -*-
import os
from datetime import datetime
import requests
from urllib.request import urlopen
from alibabacloud_imageenhan20190930.client import Client as ImageEnhanClient
from alibabacloud_imageenhan20190930.models import ColorizeImageAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import io
import base64
from config import Config as myConfig






def image_colorized(image_base64: str):
    SAVE_PATH = myConfig.PATH_IMAGE_COLORIZED

    # 尝试解码 Base64 数据
    try:
        image_data = base64.b64decode(image_base64, validate=True)
    except Exception as e:
        print("❌ Base64 解码失败，请检查输入是否为有效的 Base64 字符串:", e)
        return None

    # 配置客户端
    config = Config(
        access_key_id="LTAI5tEjriqJU1PhpsG31VDA",
        access_key_secret="jYr2LWv3ohluUvbSvnSlMkVAtcHYu4",
        endpoint='imageenhan.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )

    # 构建请求对象
    colorize_request = ColorizeImageAdvanceRequest()
    colorize_request.image_urlobject = io.BytesIO(image_data)

    runtime = RuntimeOptions()

    try:
        client = ImageEnhanClient(config)
        response = client.colorize_image_advance(colorize_request, runtime)

        # 获取增强后的图像URL
        enhanced_image_url = response.body.data.image_url
        print("上色后图像URL:", enhanced_image_url)

        # 下载图像并返回Base64编码的数据
        with requests.get(enhanced_image_url, stream=True) as r:
            r.raise_for_status()
            image_bytes = b''.join(chunk for chunk in r.iter_content(chunk_size=8192))
            with open(SAVE_PATH, 'wb') as f:
                f.write(image_bytes)
            print("✅ 上色完成，图像已加载到内存")
            return base64.b64encode(image_bytes).decode('utf-8')

    except Exception as e:
        print("❌ 处理失败:", e)
        print("错误代码:", getattr(e, 'code', '无'))
        return None